package com.idroid.widget;

import android.content.Context;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.widget.TextView;

public class KuNumTextView extends TextView {
    private final String SPACE = "\u0020";
    private String mOldTxt;
    private int mFirstLength = 3;
    private int mOtherLength = 4;

    public KuNumTextView(Context context) {
        super(context);
    }

    public KuNumTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public KuNumTextView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    /**
     * 设置显示模式。默认状态下，第一段显示3位，其它每段显示4位
     */
    public void setShowType(int firstLength, int otherLength) {
        mFirstLength = firstLength;
        mOtherLength = otherLength;
    }

    public void setStr(CharSequence text) {
        mOldTxt = text.toString();
        setText(getStrWithSpace(mOldTxt));
    }

    public String getStr() {
        return null == mOldTxt ? "" : mOldTxt;
    }

    private String getStrWithSpace(String text) {
        if (TextUtils.isEmpty(text)) {
            return "";
        }

        int len = text.length();
        if (len <= mFirstLength) {
            return text;
        }

        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < len; i++) {
            if (i == mFirstLength - 1) { // 遍历到第3个字符时，添加空格
                sb.append(text.subSequence(0, mFirstLength)).append(SPACE);
            } else if (0 == (i - mFirstLength + 1) % mOtherLength) { // 遍历到第7、11、15...个字符时，添加空格
                sb.append(text.subSequence(i - mOtherLength + 1, i + 1)).append(SPACE);
            }
        }

        int yu = (len - mFirstLength) % mOtherLength;
        if (0 == yu) { // 如果余数等于0，清除最后添加的那个空格
            sb.deleteCharAt(sb.length() - 1);
        } else { // 如果余数不等于0，添加最后几个字符
            sb.append(text.subSequence(len - yu, len));
        }

        return sb.toString();
    }
}
